// 集中管理购物车相关的数据
import { defineStore } from "pinia";
import { computed, ref } from "vue";

export const useCart = defineStore(
  "cart",
  () => {
    const cartList = ref([
      { name: "一部手机", price: 998, n: 3 },
      { name: "另一部部手机", price: 1998, n: 1 },
      { name: "一部新手机", price: 9988, n: 1 },
      { name: "一部旧手机", price: 99.8, n: 4 },
    ]);
    // 状态机的action函数
    const cartAdd = (cartObj) => {
      cartList.value.push(cartObj);
      console.log(cartList.value);
    };

    // 状态机的getters数据，本质就是computed数据
    const cartTotal = computed(() => {
      let totalNum = 0;
      cartList.value.forEach((item) => {
        totalNum += item.n;
      });
      return { totalNum };
    });

    return { cartList, cartAdd, cartTotal };
  },
  { persist: true } //启用持久化存储
);
